package com.jackchong.base

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import com.jackchong.base.BaseApplication.Companion.instance
import com.jackchong.utils.JAuto
import com.jackchong.utils.ToastUtils
import com.jackchong.widget.JImageView
import com.jackchong.widget.JTextView
import com.utils.R

/**
 * author : chong.huang
 * create : 8/8/21
 * desc   :
 */
object JToast {

    private lateinit var theme: Theme
    private lateinit var appContext: Context

    fun init(appContext: Context, theme: Theme = Theme.NIGHT) {
        this.appContext = appContext
        this.theme = theme
        ToastUtils.init(appContext)
    }

    enum class Theme{
        LIGHT,
        NIGHT
    }

    enum class Type {
        SUCCESS,
        WARNING,
        ERROR
    }

    private var sToast: Toast? = null

    private fun createTip(context: Context, type: Type, message: CharSequence): Toast {
        @SuppressLint("ShowToast") val currentToast = Toast.makeText(context, "", Toast.LENGTH_SHORT)
        val toastLayout = LayoutInflater.from(context).inflate(R.layout.jtoast_tip, null)

        val contentView = toastLayout.findViewById<ViewGroup>(R.id.contentView)
        val icon = toastLayout.findViewById<JImageView>(R.id.icon)
        val content = toastLayout.findViewById<JTextView>(R.id.content)

        when (theme) {
            Theme.NIGHT -> {
                contentView.setBackgroundResource(R.drawable.shape_toast_tip_night)
                content.setTextColor(Color.WHITE)
                icon.setImageResource(
                    when (type) {
                        Type.SUCCESS -> R.drawable.img_finish
                        Type.WARNING -> R.drawable.img_warning
                        Type.ERROR -> R.drawable.img_error
                    }
                )
            }
            Theme.LIGHT -> {
                contentView.setBackgroundResource(R.drawable.shape_toast_tip_light)
                content.setTextColor(Color.BLACK)
                icon.setImageResource(
                    when (type) {
                        Type.SUCCESS -> R.drawable.img_finish_dark
                        Type.WARNING -> R.drawable.img_warning_dark
                        Type.ERROR -> R.drawable.img_error_dark
                    }
                )
            }
        }

        content.text(message)
        JAuto.auto(toastLayout)

        currentToast.view = toastLayout
        currentToast.setGravity(Gravity.CENTER, 0, 0)
        if (sToast != null) sToast!!.cancel()
        return currentToast
    }

    fun show(type: Type, content: CharSequence?) {
        sToast = createTip(appContext, type, content?: return)
        sToast!!.show()
    }
}